package com.xhy.interceptor;

import com.xhy.annotation.RequiredToken;
import com.xhy.constant.RedisPrefix;
import com.xhy.entity.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(handler instanceof HandlerMethod) {
            //1.先获取到目标方法中是由@Xxx注解
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取到目标方法。
            Method method = handlerMethod.getMethod();
            //判断目标方法是否有@Requiredtoken注解
            boolean hasRequiredToken = method.isAnnotationPresent(RequiredToken.class);
            //2.有注解查看request里面是否有token参数
            if (hasRequiredToken) {
                String token = request.getParameter("token");
                if (StringUtils.isEmpty(token)) {
                    throw new RuntimeException("token无效。。。。");
                }
                //3.获取token
                User user = (User) redisTemplate.opsForValue().get(RedisPrefix.USER_TOKEN_KEY + token);
                if (ObjectUtils.isEmpty(user)) {
                    throw new RuntimeException("token无效。。。。");
                }
                //把查询出来的user对象放入到了request作用域
                request.setAttribute("user", user);
            }
        }
        //放行请求
        return true;
    }
}
